// pages/packageA/detail/detail.js
import Dialog from '@vant/weapp/dialog/dialog';
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: app.globalData.isIphoneX,
    nowDate: "", // 当前时间
    head: '/common/images/yushou/head.png',
    goodsId: "", // 商品id
    detail: {}, // 商品信息
    renewList: [], //更新信息
    renewData: '',
    selectFlag: 0, // 商品类别选择
    drawFlag: false, // 领取优惠券标识
    risk: '', // 风险提示
    show: false, // 购买弹框
    show1: false, // 分享弹框
    shareImg: '', // 分享图片
    show2: false, // 保存图片
    show3: false, // 放大图片
    show4: false, // 产品参数

    show5: false, // 尾款
    shopList: [], // 推荐产品列表
    endMsg: "",
    orderDetail: {
      orderStatus: "1",
      presaleStatus: "4",
    }, // 订单详情
    carList: [], // 正常列表
    address: "", // 地址详情
    freightPrice: 0, // 邮费
    shopPrice: 0,
    checkAllFlag: false,

    timeIntervalSingle: '', // 延时器
    timeList: ['00', '00', '00', '00'], // 预售倒计时
    front_price_ratio: 16, // 定金比例
    end_pay_day: 14, // 尾款结束的天数
    infoFlag: 1 // TAB标识
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('==== options ====', options)
    // options.id = 310
    if (options.scene) {
      console.info('==== scene ====', decodeURIComponent(options.scene))
      options.id = decodeURIComponent(options.scene).split('&')[0]
      options.userId = decodeURIComponent(options.scene).split('&')[1]
      options.grouponNo = decodeURIComponent(options.scene).split('&')[2]
      options.drawFlag = decodeURIComponent(options.scene).split('&')[3] == 'v1' ? true : ''
      console.log('==== options ====', options)
    }
    this.setData({
      goodsId: options.id,
      userId: options.userId,
      grouponNo: options.grouponNo,
      drawFlag: options.drawFlag
    })
    this.getRisk()
  },

  //  获取风险提示文案
  getRisk() {
    wx.get('/api/config/configKey?key=front_price_ratio', res => {
      if (res.code == 200) {
        this.setData({
          front_price_ratio: res.msg * 100
        })
      }
    }, fail => {})
    wx.get('/api/config/configKey?key=end_pay_day', res => {
      if (res.code == 200) {
        this.setData({
          end_pay_day: res.msg
        })
      }
    }, fail => {})
  },

  // 选择回报选择
  tabClick(e) {
    console.log(e)
    this.setData({
      selectFlag: e.currentTarget.dataset['index']
    })
  },

  // 点击下面公告
  infoClick(e) {
    this.setData({
      infoFlag: e.currentTarget.dataset['flag']
    })
  },

  toZhao() {
    let url = 'https://pro.ciyuanjuhe.com/doc/licence1.png'
    wx.previewImage({
      showmenu: false,
      urls: ['https://pro.ciyuanjuhe.com/doc/licence2.jpg', 'https://pro.ciyuanjuhe.com/doc/licence1.png'] // 需要预览的图片http链接列表
    })
  },

  // 跳转确认订单
  toOrderConfirm() {
    if (this.data.detail.goodsProd[this.data.selectFlag].number <= 0 || this.data.detail.status != '1') {
      return
    }
    let that = this
    wx.setStorage({
      key: "shopDetail",
      data: {
        selectFlag: this.data.selectFlag,
        userId: this.data.userId,
        grouponNo: this.data.grouponNo,
        ...this.data.detail
      },
      success() {
        that.setData({
          show: false
        })
        let url = '/pages/packageA/orderConfirm/orderConfirm'
        if (that.data.drawFlag) {
          url += '?drawFlag=true'
        }
        wx.navigateTo({
          url
        })
      }
    })
  },

  // 跳转协议
  jumpAgree(e) {
    let url
    if (e.currentTarget.dataset.type == 1) {
      url = encodeURIComponent(app.globalData.host + '/doc/refund.html')
      wx.navigateTo({
        url: `/pages/webview/webview?url= ${url}`,
      })
    } else {

    }
  },

  // 跳转问卷
  toWenQuan() {
    wx.navigateTo({
      url: '/pages/wenjuan/wenjuan',
    })
  },

  // 分享
  share(e) {
    let api = '/api/goods/'
    if (e.currentTarget.dataset.type == 'link') {
      api += `shareUrl?goodsId=${this.data.goodsId}`
    } else if (e.currentTarget.dataset.type == 'link_wb') {
      api += `shareUrl?goodsId=${this.data.goodsId}&urlType=1`
    } else {
      api += `shareImage?goodsId=${this.data.goodsId}`
    }
    wx.get(api, res => {
      console.log(e.currentTarget.dataset.type, res)
      if (res.code == 200) {
        if (e.currentTarget.dataset.type == 'link' || e.currentTarget.dataset.type == 'link_wb') {
          wx.setClipboardData({
            data: res.data.shareUrl,
            success(_res) {
              wx.getClipboardData({
                success(__res) {
                  console.log(__res.data) // data
                }
              })
            }
          })
        } else {
          wx.showLoading({
            mask: true
          })
          this.setData({
            shareImg: res.data.shareImg,
            show2: true,
            show1: false
          })
        }
      }
    }, fail => {})
  },

  imageLoad() {
    console.info('==== 图片加载完成 ====')
    wx.hideLoading()
  },

  // 保存图片
  save() {
    let that = this
    wx.showLoading({
      mask: true
    })
    wx.getImageInfo({
      src: that.data.shareImg,
      success(ress) {
        console.log(ress)
        wx.saveImageToPhotosAlbum({
          filePath: ress.path,
          success(res) {
            console.log(res)
            wx.hideLoading()
            that.setData({
              show2: false
            })
            wx.showToast({
              title: '图片保存成功',
              icon: 'none',
              duration: 2000
            })
          }
        })
      }
    })

  },

  lookGood() {
    wx.post(`${wx.api.goodAdd}${this.data.goodsId}`, {}, res => {
      console.log('==== lookGood ====', res)
      if (res.code == 200) {
        this.getDetail()
        Dialog.alert({
          title: '看好成功',
          message: '实时获取最新项目进度',
          confirmButtonText: '好的'
        })
      }
    })
  },

  lookNoGood() {
    Dialog.confirm({
      title: '确认取消看好？',
      message: '取消后将收不到预定开始提示',
      confirmButtonText: '取消看好',
      cancelButtonText: '不取消'
    }).then(() => {
      wx.get(`${wx.api.goodRemove}${this.data.goodsId}`, res => {
        console.log('==== lookNoGood ====', res)
        if (res.code == 200) {
          this.getDetail()
          Dialog.alert({
            title: '温馨提示',
            message: '已取消',
            confirmButtonText: '好的'
          })
        }
      })
    })
  },

  toRenew() {
    wx.navigateTo({
      url: `/pages/packageA/renew/renew?goodsId=${this.data.goodsId}`
    })
  },

  toRenewDetail(e) {
    let id = this.data.detail.goodsRenew.id
    wx.navigateTo({
      url: `/pages/packageA/renewDetail/renewDetail?id=${id}`
    })
  },

  toCommenList() {
    wx.navigateTo({
      url: `/pages/packageA/commentList/commentList?goodsId=${this.data.goodsId}&name=${this.data.detail.name}&picUrl=${this.data.detail.picUrl}`
    })
  },

  // 跳转商城详情
  toShopDetail() {
    wx.navigateTo({
      url: `/pages/shopDetail/shopDetail?id=${this.data.detail.mallGoodsId}&fromPage=detial`
    })
  },

  showPopup() {
    if (this.data.detail.status == 4) { // 尾款
      this.getCarList()
    } else { // 预售
      this.setData({
        show: true
      });
    }
  },

  onClose() {
    this.setData({
      show: false
    });
  },

  showPopup1() {
    this.setData({
      show1: true
    });
  },

  showPopup2() {
    this.setData({
      show2: true
    });
  },

  showPopup3() {
    this.setData({
      show3: true
    });
  },

  showPopup4() {
    this.setData({
      show4: true
    });
  },

  onClose1() {
    this.setData({
      show1: false
    });
  },

  onClose2() {
    this.setData({
      show2: false
    });
  },

  onClose3() {
    this.setData({
      show3: false
    });
  },

  onClose4() {
    this.setData({
      show4: false
    });
  },

  onClose5() {
    this.setData({
      show5: false
    });
  },

  // 返回页面顶部
  scrollTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // let a = wx.getAccountInfoSync().miniProgram.envVersion
    this.getDetail()
    let now = new Date()
    let year = now.getFullYear()
    let month = (now.getMonth() + 1).toString().padStart(2, '0')
    let day = now.getDate().toString().padStart(2, '0')
    this.setData({
      nowDate: year + month + day
    })
  },

  getDetail() {
    wx.get("/api/goods/detail?goodsId=" + this.data.goodsId, res => {
      console.log('==== detail ===', res)
      // 处理商品已购买价格
      res.data.totalAmount = Math.floor((res.data.totalAmount * 100 + res.data.dummyMoney * 100)) / 100
      // 处理商品图片富文本
      res.data.detail = res.data.detail.replace(/\/\>/gi, ' style="display:block" width="100%" height=""/>')
      // 处理商品类型 数组转成字符串
      res.data.goodsProd = res.data.goodsProd.map(item => {
        return {
          ...item,
          specificationsText: item.specifications.join('+')
        }
      })
      if (res.data.status == 6) res.data.status = 5
      res.data.buyNum = res.data.goodsUnlockeds[res.data.goodsUnlockeds.length - 1].value
      res.data.startNum = res.data.goodsUnlockeds[0].value
      let startNum = res.data.goodsUnlockeds[0].value
      res.data.goodsUnlockeds.forEach((item, index) => {
        if (index != 0 && index != res.data.goodsUnlockeds.length - 1) {
          var left = Math.floor(((item.value - startNum) / (res.data.buyNum - startNum)) * 100)
          item.left = "left:" + left + "%"
        }
      })
      // 处理剩余天数 
      let nowTime = new Date() * 1
      let endTime = new Date(res.data.endTime.replace(/-/g, '/')) * 1
      let endDay = Math.floor((endTime - nowTime) / (1000 * 3600 * 24))
      res.data.endDay = endDay > 0 ? endDay : 0
      let goodsAttrText = ''
      res.data.goodsAttr.forEach((item, index) => {
        if (index == 0) {
          goodsAttrText += item.attribute
        } else {
          goodsAttrText += ' · ' + item.attribute
        }
      });
      res.data.goodsAttrText = goodsAttrText
      this.setData({
        detail: res.data
      })
      this.singleCountDown()
    }, fail => {})
  },

  // 商品列表
  getShopList() {
    wx.get(`/api/goods/rankings`, res => {
      console.log('==== goodList ====', res)
      if (res.data.length > 0) {
        this.setData({
          shopList: res.data.slice(0, 4)
        })
      }
    })
  },

  // 跳转商品详情
  toDetail(e) {
    wx.navigateTo({
      url: '/pages/shopDetail/shopDetail?id=' + e.currentTarget.dataset['id']
    })
  },

  // 获取尾款订单
  getCarList() {
    this.setData({
      shopPrice: 0,
      checkAllFlag: false
    })
    wx.get(`${wx.api.payEndAll}?goodsSn=${this.data.detail.goodsSn}`, res => {
      console.log('==== payEndAll ====', res)
      if (res.code == 200 && res.data.length > 0) {
        this.setData({
          carList: res.data,
        })
        this.getAddress()
      } else {
        this.setData({
          carList: [],
          endMsg: res.msg
        })
        this.getShopList()
      }
      this.setData({
        show5: true,
      })
    })
  },

  // 单选
  changeSignFlag(e) {
    let item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    this.setData({
      [`carList[${index}].checked`]: !item.checked
    })
    this.getShopPrice()
    if (this.data.carList.findIndex(item => !item.checked) == -1) {
      this.setData({
        checkAllFlag: true
      })
    } else {
      this.setData({
        checkAllFlag: false
      })
    }
  },

  // 全选 全不选
  checkALL() {
    let flag = this.data.checkAllFlag
    this.setData({
      checkAllFlag: !this.data.checkAllFlag,
    })
    this.data.carList.forEach((item, index) => {
      this.setData({
        [`carList[${index}].checked`]: !flag,
      })
    })
    this.getShopPrice()
  },

  // 计算总价
  getShopPrice() {
    let checkList = this.data.carList.filter(item => item.checked)
    this.setData({
      freightPrice: 0,
    })
    if (checkList.length > 0) {
      let shopPrice = 0
      checkList.forEach((item, index) => {
        shopPrice += item.endPrice * 100
        wx.get(`${wx.api.mallchooseAddress}${this.data.address.id}?goodsId=${item.goodsId}`, res => {
          console.log('==== chooseAddress ===', res)
          if (res.code == 200) {
            this.setData({
              // [`carList[${index}].freightPrice`]: (res.data).toFixed(2),
              freightPrice: this.data.freightPrice += res.data,
            })
          }
        })
      })
      this.setData({
        shopPrice: shopPrice / 100
      })
    } else {
      this.setData({
        shopPrice: 0,
        freightPrice: 0,
      })
    }
  },

  // 获取地址
  getAddress() {
    let that = this
    wx.get("/api/address/list", res => {
      console.log('==== list ===', res)
      if (res.data.length > 0) {
        let index = 0
        try {
          var value = wx.getStorageSync('addressSelect')
          if (value) {
            index = value
          }
        } catch (e) {
          // Do something when catch error
        }
        this.setData({
          address: res.data[index]
        })
        wx.removeStorage({
          key: 'addressSelect'
        })
      }
    }, fail => {})
  },

  // 选择地址
  selectAddress(e) {
    wx.navigateTo({
      url: `../../addressList/addressList?fromType=orderConfirm`
    })
  },

  // 支付尾款
  endPay() {
    if (this.data.shopPrice == 0) return
    let params = {
      addressId: this.data.address.id,
      freightPrice: this.data.freightPrice.toFixed(2),
      goodsId: this.data.goodsId,
      orderIds: [],
      orderMoney: (Number(this.data.shopPrice) + Number(this.data.freightPrice)).toFixed(2)
    }
    this.data.carList.forEach(item => {
      if (item.checked) params.orderIds.push(item.id)
    })
    wx.showLoading({
      mask: true
    })
    wx.post(wx.api.endAllSubmit, params, res => {
      console.log('==== endPay ===', res)
      if (res.code == 200) {
        this.doWxPay(res)
      }
    }, fail => {})
  },

  //小程序发起微信支付
  doWxPay(param) {
    wx.requestPayment({
      timeStamp: param.data.timeStamp, //记住，这边的timeStamp一定要是字符串类型的，不然会报错
      nonceStr: param.data.nonceStr,
      package: param.data.package,
      signType: param.data.signType,
      paySign: param.data.paySign,
      success(event) {
        console.log('==== success ====', event);
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1000
        });
      },
      fail(error) {
        console.log('==== error ====', error)
        wx.showToast({
          title: '支付失败',
          icon: 'error',
          duration: 1000
        });
      },
      complete(res) {
        wx.hideLoading()
        console.log("pay complete", res)
        let result = "success"
        if (res.errMsg != 'requestPayment:ok') { // 失败
          result = "fail"
        }
        setTimeout(() => {
          wx.reLaunch({
            url: `/pages/result/result?result=${result}&type=weikuan&url=/pages/packageA/orderList/orderList`,
          })
        }, 1000);
      }
    });
  },

  // 复制文案
  copyText(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.no,
      success(ress) {
        wx.getClipboardData({
          success(res) {
            console.log(res.data) // data
          }
        })
      }
    })
  },

  // 倒计时定时器
  singleCountDown() {
    let endTime
    if (this.data.detail.status == 0) {
      endTime = new Date(this.data.detail.startTime.replace(/-/g, "/")).getTime()
    } else {
      endTime = new Date(this.data.detail.endTime.replace(/-/g, "/")).getTime()
    }
    var currentTime = new Date().getTime(); //当前时间时间戳
    var time = (endTime - currentTime);
    // // 商品已过购买期限
    if (time > 0) {
      let d, h, m, s;
      d = Math.floor(time / 1000 / 60 / 60 / 24);
      h = Math.floor(time / 1000 / 60 / 60 % 24);
      m = Math.floor(time / 1000 / 60 % 60);
      s = Math.floor(time / 1000 % 60);
      var timeIntervalSingle = setTimeout(this.singleCountDown, 1000);
      this.setData({
        timeList: [this.timeFormat(d), this.timeFormat(h), this.timeFormat(m), this.timeFormat(s)],
        timeIntervalSingle
      })
    } else {
      console.log(' 666666666666666666666 ', this.data.timeIntervalSingle)
      this.setData({
        timeList: ['00', '00', '00', '00']
      })
      if (this.data.timeIntervalSingle) {
        clearTimeout(this.data.timeIntervalSingle)
        this.getDetail()
      }
    }
  },

  //时间显示小于10的前面补0方法
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: this.data.detail.name,
      path: `/pages/packageA/detail/detail?id=${this.data.goodsId}`,
      imageUrl: this.data.detail.picUrl
    }
  },

  /**
   * 用户点击右上角分享转发到朋友圈
   */
  onShareTimeline() {
    return {
      title: this.data.detail.name,
      query: `id=${this.data.goodsId}`,
      imageUrl: this.data.detail.picUrl
    }
  }
})